#-*-coding:utf-8-*-
'''
Created on 2012-6-9
C:/Users/zhaoyh/workspace/yfmis/addons/PF/Common/enum.py
@author: zhaoyh
'''
from xml.etree import ElementTree
import web
xml_file="./enum.xml"
root = ElementTree.parse(xml_file).getroot()
enum = ElementTree.parse(xml_file)
def get_enums2():
    result =[]
    rules = root.getiterator("rule")
    for rule in rules:
        l={}        
        l["id"]=rule.get("id")        
        for subnode in rule.getchildren():
            l[subnode.tag]=subnode.text
        result.append(web.storage(l))
    return result

def get_enums_all():
#    root = ElementTree.parse(filename).getroot()
    #获取文件描述
    result =[]
    rules = root.findall('rule')
    for rule in rules:
        d={}
        d['ruleid']=rule.get("id")  
        d['name'] = rule.find('name').text
        d['types'] = rule.find('types').text
        d['model'] = rule.find('model').text
        d['content'] = rule.find('content').text
        result.append(web.storage(d))
    return result
        
def get_enum(rule_id):
#    root = ElementTree.parse(filename).getroot()
    #获取文件描述
    result =[]
    rules = root.findall('rule')
    for rule in rules:
        if  rule.get('id') == rule_id:  
            d={}
            d['ruleid']=rule.get("id")  
            d['name'] = rule.find('name').text
            d['types'] = rule.find('types').text
            d['model'] = rule.find('model').text
            d['content'] = rule.find('content').text
            result.append(web.storage(d))
    return result
    
def add_enum(rule_id,tname,ttypes,tmodel,tcontent):
    """
    重复的怎么办？
    """
    
    root=enum.getroot()
    rule = ElementTree.Element("rule",id=rule_id)
    name=ElementTree.Element("name")
    name.text=tname
    rule.append(name)
    types = ElementTree.Element("types")
    types.text=ttypes   
    rule.append(types)
    model = ElementTree.Element("model")
    model.text=tmodel
    rule.append(model) 
    content = ElementTree.Element("content")
    content.text=tcontent
    rule.append(content) 
#    rules = root.find("data")
    root.append(rule)
    enum.write(xml_file, encoding="utf-8")
    
def edit_enum(rule_id, **field):
    rules = enum.getiterator("rule")
    for rule in rules:
        if  rule.get('id') == rule_id:
            for key,v in field.items():
                rule.find(key).text=v
    enum.write(xml_file, encoding="utf-8")
    
def delete_enum(rule_id):
    root=enum.getroot()
    rules = enum.getiterator("rule")
    for rule in rules:
        if  rule.get('id') == rule_id:
            print rule.get('id') 
            root.remove(rule)
    enum.write(xml_file, encoding="utf-8")
    

if __name__ == "__main__":
    add_enum("aa","1","2","3","4")
    delete_enum("122334")
    edit_enum("FORM_d",**{"name":"changename","types":"types"})
    print get_enum("FORM_d")
#    test_xmltostring()
#    test_laod_xml()
